package com.aaron.android.battery;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public final class BootCompletedReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())
				&& AppConfig.getInstance(context).isShowStatusBarIcon()) {

			if (AppConfig.getInstance(context).isShowStatusBarIcon()) {
				startService(context);
			}
		}
	}

	public static void startService(Context context) {

		final int retryCount = 3;

		Intent batteryInfoStatusBarIntent = initializeBatteryInfoStatusBarIntent(context);

		for (int retryTime = 0; retryTime < retryCount; retryTime++) {
			try {
				context.startService(batteryInfoStatusBarIntent);
				break;
			} catch (Exception e) {
				if (retryTime + 1 == retryCount) {
					Log.d("BootCompletedReceiver", "Start service failed."
							+ batteryInfoStatusBarIntent.getPackage(), e);
					Toast.makeText(
							context,
							context.getResources().getText(R.string.error_show),
							1000).show();
				}
				continue;
			}
		}
	}

	private static Intent initializeBatteryInfoStatusBarIntent(Context context) {
		Intent batteryInfoStatusBarIntent = new Intent(context, BatteryInfoStatusBarService.class);
		batteryInfoStatusBarIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		return batteryInfoStatusBarIntent;
	}
}